package it.clariter.web.action;

import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;

import it.clariter.dao.DocumentoDAO;
import it.clariter.model.Documento;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class EsportaDocumentoAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if(request.getSession().getAttribute("utente")==null){
			response.sendRedirect("login.jsp");
		}
		
		HttpSession session = request.getSession();
		String id = (String) session.getAttribute("idDocumento");
		esporta(Integer.valueOf(id), response);
		return mapping.findForward("ok");
		
	}
	public void esporta (int id, HttpServletResponse response) throws DocumentException, IOException, SQLException {
		
		Documento doc = new DocumentoDAO().get(id);


		ServletOutputStream outputstream = response.getOutputStream();
		Document document = new Document(PageSize.A4, 108, 72, 30, 72);
		PdfWriter writer = PdfWriter.getInstance(document, outputstream);

		document.open();

		///-----Added Some Title----///


		response.setContentType("application/pdf");
		response.setHeader("Content-Disposition", "attachment; filename="+doc.getProtocollo());
		byte[] bytes = doc.getDocumento().getBytes(1, (int) doc.getDocumento().length());
		InputStream is = doc.getDocumento().getBinaryStream();
		PdfReader pdfReader = new PdfReader(is, bytes);
		PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
		PdfImportedPage page;
		int pageOfCurrentReaderPDF = 0;
		while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
		    if (pageOfCurrentReaderPDF > 0) {
		        document.newPage();
		    }
		    pageOfCurrentReaderPDF++;
		    page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
		    cb.addTemplate(page, 0, 0);
		}
		pageOfCurrentReaderPDF = 0;
		outputstream.flush();
		document.close();
		outputstream.close();
		
	}
}
